package com.zhongkun.datahome.service.export.handler;

import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.nio.charset.StandardCharsets;

public class DynamicColumnWidthStrategy extends AbstractColumnWidthStyleStrategy {

    @Override
    protected void setColumnWidth(CellWriteHandlerContext context) {
        WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
        Boolean isHead = context.getHead();
        Integer columnIndex = context.getColumnIndex();
        if (isHead) {
            // 计算表头内容的最大宽度（行号0）
            int headerWidth = calculateMaxWidth(writeSheetHolder, columnIndex, 0);
            writeSheetHolder.getSheet().setColumnWidth(columnIndex, headerWidth * 256);
        } else {
            // 计算数据内容的最大宽度（行号≥1）
            int dataWidth = calculateMaxWidth(writeSheetHolder, columnIndex, 1);
            writeSheetHolder.getSheet().setColumnWidth(columnIndex, dataWidth * 256);
        }
    }

    private int calculateMaxWidth(WriteSheetHolder writeSheetHolder, int columnIndex, int startRow) {
        Sheet sheet = writeSheetHolder.getSheet();
        int lastRowNum = sheet.getLastRowNum();
        int maxWidth = 0;
        for (int rowNum = startRow; rowNum <= lastRowNum; rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row == null) continue;
            Cell cell = row.getCell(columnIndex);
            if (cell == null) continue;
            String cellValue = getCellValueAsString(cell); // 将单元格内容转为字符串
            int width = cellValue.getBytes(StandardCharsets.UTF_8).length; // 计算字节数（近似字符数）
            maxWidth = Math.max(maxWidth, width);
        }
        return maxWidth;
    }

    private String getCellValueAsString(Cell cell) {
        // 根据单元格类型获取值（字符串、数字、日期等）
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return DateUtil.getJavaDate(cell.getNumericCellValue()).toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }
}